<?php
include_once HTKOU_ROOT.'/uc_client/config.inc.php';
include_once HTKOU_ROOT.'/uc_client/client.php';

function count_failed_logins()
 {
  global $db_settings, $connid;
  $result = @mysql_query("SELECT logins FROM ".$db_settings['login_control_table']." WHERE ip='".mysql_real_escape_string($_SERVER["REMOTE_ADDR"])."'", $connid); 
  if(mysql_num_rows($result)==1)
   {
    @mysql_query("UPDATE ".$db_settings['login_control_table']." SET logins=logins+1 WHERE ip='".mysql_real_escape_string($_SERVER["REMOTE_ADDR"])."'", $connid);
   } 
  else
   {
    @mysql_query("INSERT INTO ".$db_settings['login_control_table']." (time,ip,logins) VALUES (NOW(),'".mysql_real_escape_string($_SERVER["REMOTE_ADDR"])."',1)", $connid);
   }
  mysql_free_result($result);
 }

if(!defined('IN_INDEX')) 
 { 
  header('location: index.php'); 
  exit();
 }

if(isset($_REQUEST['action'])) $action = $_REQUEST['action'];
if(isset($_POST['pwf_submit'])) $action = 'pw_forgotten_submitted';

// import posted or got username and password: 
if(isset($_POST['username']) && trim($_POST['username'])!='') $request_username = $_POST['username'];
elseif(isset($_GET['username']) && trim($_GET['username'])!='') $request_username = $_GET['username'];
if(isset($_POST['userpw']) && trim($_POST['userpw'])!='') $request_userpw = $_POST['userpw'];
elseif(isset($_GET['userpw']) && trim($_GET['userpw'])!='') $request_userpw = $_GET['userpw'];

// look if session is active, if not: login
if(isset($_SESSION[$settings['session_prefix'].'user_id']) && empty($action))
 {
  $action = "logout";
 }
elseif (empty($_SESSION[$settings['session_prefix'].'user_id']) && isset($request_username) && isset($request_userpw))
 {
  $action = "do_login";
 }
elseif (empty($_SESSION[$settings['session_prefix'].'user_id']) && isset($_COOKIE[$settings['session_prefix'].'auto_login']) && isset($settings['autologin']) && $settings['autologin'] == 1)
 {
  $action = "auto_login";
 }
elseif (empty($_SESSION[$settings['session_prefix'].'user_id']) && empty($action) && empty($_GET['activate']))
 {
  $action = "login";
 }
elseif (empty($_SESSION[$settings['session_prefix'].'user_id']) && empty($action) && isset($_GET['activate']))
 {
  $action = "activate";
 }

if(isset($_GET['login_message'])) $smarty->assign('login_message',$_GET['login_message']);

// clear failed logins and check if there are failed logins from this ip:
if($settings['temp_block_ip_after_repeated_failed_logins']==1)
 {
  @mysql_query("DELETE FROM ".$db_settings['login_control_table']." WHERE time < (NOW()-INTERVAL 10 MINUTE)", $connid);
  $failed_logins_result = @mysql_query("SELECT logins FROM ".$db_settings['login_control_table']." WHERE ip='".mysql_real_escape_string($_SERVER["REMOTE_ADDR"])."'", $connid); 
  if(mysql_num_rows($failed_logins_result)==1)
   {
    $data = mysql_fetch_array($failed_logins_result);
    if($data['logins']>=3) $action = 'ip_temporarily_blocked';
   }
  mysql_free_result($failed_logins_result);
 }
 
switch ($action)
 {
  case "do_login":
   if(isset($request_username) && isset($request_userpw))
    {
     $result = mysql_query("SELECT user_id, user_name, user_real_name, user_pw, user_type, UNIX_TIMESTAMP(last_login) AS last_login, UNIX_TIMESTAMP(last_logout) AS last_logout, thread_order, user_view, sidebar, fold_threads, thread_display, time_difference, activate_code FROM ".$db_settings['userdata_table']." WHERE lower(user_name) = '".mysql_real_escape_string(strtolower($request_username))."'", $connid) or raise_error('database_error',mysql_error());
     if (mysql_num_rows($result) == 1)
      {
       $feld = mysql_fetch_array($result);

       if($feld["user_pw"] == md5($request_userpw))
        {
         if(trim($feld["activate_code"]) != '')
          {
           header("location: index.php?mode=login&login_message=account_not_activated");
           exit;
          }

         if(isset($_POST['autologin_checked']) && isset($settings['autologin']) && $settings['autologin'] == 1)
          {
           $cookie_auto_login_code = md5(uniqid(rand()));
           $auto_login_code = md5($cookie_auto_login_code);
           setcookie($settings['session_prefix'].'auto_login',$feld['user_id'].'.'.$cookie_auto_login_code,time()+(3600*24*30));
          }
         else
          {
           $auto_login_code = '';
           setcookie($settings['session_prefix'].'auto_login','',0);
          }
        
         $user_id = $feld["user_id"];
         $user_name = $feld["user_name"];
         $user_type = $feld["user_type"];
         #$usersettings['view'] = $feld["user_view"];
         $usersettings['newtime'] = $feld['last_logout'];
         $usersettings['user_view'] = $feld['user_view'];
         $usersettings['time_difference'] = $feld['time_difference'];  
         $usersettings['thread_order'] = $feld['thread_order'];
         $usersettings['sidebar'] = $feld['sidebar'];  
         $usersettings['fold_threads'] = $feld['fold_threads'];
         $usersettings['thread_display'] = $feld['thread_display'];
         $usersettings['page'] = 1;
         $usersettings['category'] = 0; 
         $usersettings['latest_postings'] = 1;
         #$usersettings['tag_cloud'] = 1;    
         $_SESSION[$settings['session_prefix'].'user_id'] = $user_id;
         $_SESSION[$settings['session_prefix'].'user_name'] = $user_name;
         $_SESSION[$settings['session_prefix'].'user_type'] = $user_type;
         $_SESSION[$settings['session_prefix'].'usersettings'] = $usersettings;
         $_SESSION[$settings['session_prefix'].'user_real_name'] = $feld['user_real_name'];  // added by Terry
         @mysql_query("UPDATE ".$db_settings['userdata_table']." SET logins=logins+1, last_login=NOW(), last_logout=NOW(), registered=registered, auto_login_code='".mysql_real_escape_string($auto_login_code)."' WHERE user_id='".$user_id."'", $connid);
       
         // auto delete spam:
         if($user_type>0 && $settings['auto_delete_spam']>0) @mysql_query("DELETE FROM ".$db_settings['forum_table']." WHERE time < (NOW() - INTERVAL ".$settings['auto_delete_spam']." HOUR) AND spam=1", $connid);
       
         if ($db_settings['useronline_table'] != "")
          {
           @mysql_query("DELETE FROM ".$db_settings['useronline_table']." WHERE ip = '".$_SERVER['REMOTE_ADDR']."'", $connid);
          }

         $f_mode = '';
         if(isset($_POST['back'])) $f_mode .= '?mode='.$_POST['back'];
         if(isset($_POST['id'])) $f_mode .= '&id='.$_POST['id'].'&back=entry';
         
         
         list($uc_uid, $uc_username, $uc_password, $uc_email) = uc_user_login($request_username, $request_userpw);
         error_log("login uc_uid: ".$uc_uid."\n", 3, "C:/poc/log/HTKou.log");	   
         
         if($uc_uid > 0) {
			echo uc_user_synlogin($uc_uid);
		 }
		  
		 echo "<script language=javascript>setTimeout(\"location.href='index.php".$f_mode."'\",1);</script>";
		 
         //header('Location: index.php'.$f_mode);
         exit;
        }
       else 
        {
         if($settings['temp_block_ip_after_repeated_failed_logins']==1) count_failed_logins();
         #header("location: index.php?mode=login&login_message=login_failed");
         #exit;
         $action = 'login';
         $login_message='login_failed';
        }
     }
    else 
     {
      if($settings['temp_block_ip_after_repeated_failed_logins']==1) count_failed_logins();
      #header("location: index.php?mode=login&login_message=login_failed");
      #exit;
      $action = 'login';
      $login_message='login_failed';
     }
    }
   else 
    {
     if($settings['temp_block_ip_after_repeated_failed_logins']==1) count_failed_logins();
     #header("location: index.php?mode=login&login_message=login_failed");
     #exit;
     $action = 'login';
     $login_message='login_failed';
    }
  break;

  case "auto_login":
   if(empty($_SESSION[$settings['session_prefix'].'user_id']) && isset($_COOKIE[$settings['session_prefix'].'auto_login']) && isset($settings['autologin']) && $settings['autologin'] == 1)
    {
     $auto_login_array = explode(".",$_COOKIE[$settings['session_prefix'].'auto_login']);
     $c_uid = $auto_login_array[0];
     $c_uid = intval($c_uid);
     $result = mysql_query("SELECT user_id, user_name, user_real_name, user_pw, user_type, UNIX_TIMESTAMP(last_login) AS last_login, UNIX_TIMESTAMP(last_logout) AS last_logout, thread_order, user_view, sidebar, fold_threads, thread_display, time_difference, auto_login_code, activate_code FROM ".$db_settings['userdata_table']." WHERE user_id = '".$c_uid."'", $connid) or raise_error('database_error',mysql_error());
     if(mysql_num_rows($result) == 1 && isset($auto_login_array[1]) && trim($auto_login_array[1])!='')
      {
       $feld = mysql_fetch_array($result);
       if(trim($feld['auto_login_code'])!='' && $feld['auto_login_code'] == md5($auto_login_array[1]) && trim($feld["activate_code"]==''))
        {
         $user_id = $feld["user_id"];
         $user_name = $feld["user_name"];
         $user_type = $feld["user_type"];
         #$usersettings['view'] = $feld["user_view"];
         $usersettings['time_difference'] = $feld["time_difference"];
         $usersettings['newtime'] = $feld["last_logout"];
         $usersettings['user_view'] = $feld["user_view"]; 
         $usersettings['thread_order'] = $feld['thread_order'];
         $usersettings['sidebar'] = $feld['sidebar'];
         $usersettings['fold_threads'] = $feld['fold_threads'];
         $usersettings['thread_display'] = $feld['thread_display'];
         $usersettings['time_difference'] = $feld["time_difference"]; 
         $usersettings['page'] = 1;
         $usersettings['category'] = 0;
         $usersettings['latest_postings'] = 1;
         #$usersettings['tag_cloud'] = 1;    
          
         $_SESSION[$settings['session_prefix'].'user_id'] = $user_id;
         $_SESSION[$settings['session_prefix'].'user_name'] = $user_name;
         $_SESSION[$settings['session_prefix'].'user_type'] = $user_type;
         $_SESSION[$settings['session_prefix'].'usersettings'] = $usersettings;
         $_SESSION[$settings['session_prefix'].'user_real_name'] = $feld['user_real_name'];  // added by Terry
         @mysql_query("UPDATE ".$db_settings['userdata_table']." SET logins=logins+1, last_login=NOW(), last_logout=NOW(), registered=registered WHERE user_id='".$user_id."'", $connid);
         
         // auto delete spam:
         if($user_type>0 && $settings['auto_delete_spam']>0) @mysql_query("DELETE FROM ".$db_settings['forum_table']." WHERE time < (NOW() - INTERVAL ".$settings['auto_delete_spam']." HOUR) AND spam=1", $connid);

         setcookie($settings['session_prefix'].'auto_login',$_COOKIE[$settings['session_prefix'].'auto_login'],time()+(3600*24*30));
         if($db_settings['useronline_table'] != "")
          {
           @mysql_query("DELETE FROM ".$db_settings['useronline_table']." WHERE ip = '".$_SERVER['REMOTE_ADDR']."'", $connid);
          }
          
         $f_mode = '';
         if(isset($back) && isset($id)) $f_mode .= '?mode='.$back.'&id='.$id;
         elseif(isset($id)) $f_mode .= '?id='.$id;
         elseif(isset($back)) $f_mode .= '?mode='.$back;
         
         header('Location: index.php'.$f_mode);
         exit;
        }
       else 
        {
         if($settings['temp_block_ip_after_repeated_failed_logins']==1) count_failed_logins();
         setcookie($settings['session_prefix'].'auto_login','',0);
        } 
      }
     else 
      {
       if($settings['temp_block_ip_after_repeated_failed_logins']==1) count_failed_logins();
       setcookie($settings['session_prefix'].'auto_login','',0);
      } 
     }
     else
      {
       if($settings['temp_block_ip_after_repeated_failed_logins']==1) count_failed_logins();
       setcookie($settings['session_prefix'].'auto_login','',0);
      } 
  break;

  case "logout":
   log_out($_SESSION[$settings['session_prefix'].'user_id']);
   header("location: index.php");
   exit;
  break;

  case "pw_forgotten_submitted":
   if(trim($_POST['pwf_email'])=='') $error=true;
   if(empty($error))
    {
     $pwf_result = @mysql_query("SELECT user_id, user_name, user_email FROM ".$db_settings['userdata_table']." WHERE user_email = '".mysql_real_escape_string($_POST['pwf_email'])."' LIMIT 1", $connid) or raise_error('database_error',mysql_error());
     if(mysql_num_rows($pwf_result)!=1) $error=true;
     else $field = mysql_fetch_array($pwf_result);
     mysql_free_result($pwf_result);
    }
   if(empty($error))
    {
       $pwf_code = md5(uniqid(rand()));
       $update_result = mysql_query("UPDATE ".$db_settings['userdata_table']." SET last_login=last_login, registered=registered, pwf_code='".md5($pwf_code)."' WHERE user_email = '".mysql_real_escape_string($_POST['pwf_email'])."' LIMIT 1", $connid);
       // send mail with activating link:
       $smarty->config_load($settings['language_file'],'emails');
       $lang = $smarty->get_config_vars();
       $lang['pwf_activating_email_txt'] = str_replace("[name]", $field["user_name"], $lang['pwf_activating_email_txt']);
       $lang['pwf_activating_email_txt'] = str_replace("[forum_address]", $settings['forum_address'], $lang['pwf_activating_email_txt']);
       $lang['pwf_activating_email_txt'] = str_replace("[activating_link]", $settings['forum_address'].basename($_SERVER['PHP_SELF'])."?mode=login&activate=".$field["user_id"]."&code=".$pwf_code, $lang['pwf_activating_email_txt']);
       $lang['pwf_activating_email_txt'] = stripslashes($lang['pwf_activating_email_txt']);
       $header = "From: ".$settings['forum_name']." <".$settings['forum_email'].">\n";
       $header .= "X-Sender-IP: ".$_SERVER['REMOTE_ADDR']."\n";
       $header .= "Content-Type: text/plain";
       $pwf_mailto = $field["user_name"]." <".$field["user_email"].">";
       if($settings['mail_parameter']!='')
        {
         if(@mail($pwf_mailto, $lang['pwf_activating_email_sj'], $lang['pwf_activating_email_txt'], $header,$settings['mail_parameter']))
          {
           header("location: index.php?mode=login&login_message=mail_sent"); die("<a href=\"index.php?mode=login&login_message=mail_sent\">further...</a>");
           exit;
          }
         else die($lang['mail_error']);
        }
       else
        {
         if(@mail($pwf_mailto, $lang['pwf_activating_email_sj'], $lang['pwf_activating_email_txt'], $header))
          {
           header("location: index.php?mode=login&login_message=mail_sent"); die("<a href=\"index.php?mode=login&login_message=mail_sent\">further...</a>");
           exit;
          }
         else die($lang['mail_error']);
        }
    }
   header("location: index.php?mode=login&login_message=pwf_failed");
   exit;
  break;

  case "activate":
  if (isset($_GET['activate']) && trim($_GET['activate']) != "" && isset($_GET['code']) && trim($_GET['code']) != "")
   {
    $pwf_result = mysql_query("SELECT user_id, user_name, user_email, pwf_code FROM ".$db_settings['userdata_table']." WHERE user_id = '".intval($_GET["activate"])."'", $connid);
    if (!$pwf_result) raise_error('database_error',mysql_error());
    $field = mysql_fetch_array($pwf_result);
    mysql_free_result($pwf_result);
    if ($field['user_id'] == $_GET["activate"] && $field['pwf_code'] == md5($_GET['code']))
     {
      // generate new password:
      $letters="abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
      mt_srand ((double)microtime()*1000000);
      $new_user_pw="";
      for($i=0;$i<8;$i++) { $new_user_pw.=substr($letters,mt_rand(0,strlen($letters)-1),1); }
      $encoded_new_user_pw = md5($new_user_pw);
      $update_result = mysql_query("UPDATE ".$db_settings['userdata_table']." SET last_login=last_login, registered=registered, user_pw='".$encoded_new_user_pw."', pwf_code='' WHERE user_id='".$field["user_id"]."' LIMIT 1", $connid);

      // send new password:
      $smarty->config_load($settings['language_file'],'emails');
      $lang = $smarty->get_config_vars();

      $lang['new_pw_email_txt'] = str_replace("[name]", $field['user_name'], $lang['new_pw_email_txt']);
      $lang['new_pw_email_txt'] = str_replace("[password]", $new_user_pw, $lang['new_pw_email_txt']);
      $lang['new_pw_email_txt'] = str_replace("[login_link]", $settings['forum_address'].basename($_SERVER['PHP_SELF'])."?mode=login&username=".urlencode($field['user_name'])."&userpw=".$new_user_pw, $lang['new_pw_email_txt']);
      $lang['new_pw_email_txt'] = stripslashes($lang['new_pw_email_txt']);
      $header = "From: ".$settings['forum_name']." <".$settings['forum_email'].">\n";
      $header .= "X-Sender-IP: ".$_SERVER['REMOTE_ADDR']."\n";
      $header .= "Content-Type: text/plain";
      $new_pw_mailto = $field['user_name']." <".$field['user_email'].">";
      if($settings['mail_parameter']!='')
       {
        if (@mail($new_pw_mailto, $lang['new_pw_email_sj'], $lang['new_pw_email_txt'], $header,$settings['mail_parameter']))
         {
          header("location: index.php?mode=login&login_message=pw_sent");
          die("<a href=\"index.php?mode=login&login_message=pw_sent\">further...</a>");
         }
        else die($lang['mail_error']);
       }
      else
       {
        if (@mail($new_pw_mailto, $lang['new_pw_email_sj'], $lang['new_pw_email_txt'], $header))
         {
          header("location: index.php?mode=login&login_message=pw_sent");
          die("<a href=\"index.php?mode=login&login_message=pw_sent\">further...</a>");
         }
        else die($lang['mail_error']);
       }
     }
    else
     {
      header("location: index.php?mode=login&login_message=code_invalid");
      die("<a href=\"index.php?mode=login&login_message=code_invalid\">further...</a>");
     }
   }
   else
    {
     header("location: index.php?mode=login&login_message=code_invalid");
     exit;
    }
  break;
 }

$smarty->assign('action',$action);

switch($action)
 {
  case "login":
   $smarty->assign('subnav_location','subnav_login');
   $smarty->assign('subtemplate','login.tpl.inc');
   if(isset($login_message)) $smarty->assign('login_message',$login_message);
   if(isset($_REQUEST['id'])) $smarty->assign('id',intval($_REQUEST['id']));
   if(isset($_REQUEST['back'])) $smarty->assign('back',htmlspecialchars(stripslashes($_REQUEST['back'])));
   $template = 'main.tpl';
  break;
  case "pw_forgotten":
   $breadcrumbs[0]['link'] = 'index.php?mode=login';
   $breadcrumbs[0]['linkname'] = 'subnav_login';
   $smarty->assign('breadcrumbs',$breadcrumbs);
   $smarty->assign('subnav_location','subnav_pw_forgotten');
   $smarty->assign('subtemplate','login_pw_forgotten.tpl.inc');
   $template = 'main.tpl';
  break;
  case "ip_temporarily_blocked":
   $smarty->assign('ip_temporarily_blocked',true);
   $smarty->assign('subnav_location','subnav_login');
   $smarty->assign('subtemplate','login.tpl.inc');
   $template = 'main.tpl';
  break;
 }
?>
